<?php
class Application_Model_DbTable_Product extends Zend_Db_Table_Abstract {
	protected $_name = 'tbl_product';
	protected $_primary = 'product_id';
	protected $_referenceMap = array (
			'tbl_manufacture' => array (
					'columns' => array (
							'product_manufacture_id' 
					),
					'refTableClass' => 'Application_Model_DbTable_Manufacture' 
			),
			'tbl_category' => array (
					'columns' => array (
							'product_category_id' 
					),
					'refTableClass' => 'Application_Model_DbTable_Category' 
			) 
	);
	protected $_dependentTables = array (
			'Application_Model_DbTable_ProductImage' 
	);
	const STATUS_YES = 1;
	const STATUS_NO = 0;
	const SALEOFF_CONTINUE = 1;
	
	/**
	 * lấy danh sách sản phẩm có điều kiện
	 */
	public function getList($filters = array(), $sortType = "ASC", $sortBy = null) {
		$select = $this->select ()->setIntegrityCheck ( false )->from ( $this->_name )->join ( "tbl_manufacture", "product_manufacture_id = manufacture_id", null );
		
		if (count ( $filters ) > 0) {
			
			foreach ( $filters as $key => $value ) {
				
				if ($key == "keyword" && trim ( $value ) != "") {
					$select->where ( 'product_name like ?', "%$value%" );
				}
				
				if ($key == "category" && (! ($value == null || $value == 0))) {
					$select->where ( 'product_category_id = ?', $value );
				}
				
				if ($key == "manufacture" && (! ($value == null || $value == 0))) {
					$select->where ( 'product_manufacture_id = ?', $value );
				}
				
				if ($key == "startPrice" && $value != null) {
					$select->where ( 'product_price >= ?', ( int ) $value );
				}
				
				if ($key == "endPrice" && $value != "max") {
					if ($value != null)
						$select->where ( 'product_price <= ?', ( int ) $value );
				}
				
				if ($key == "fromDate" && $value != null) {
					$select->where ( 'product_creation_time >= ?', $value );
				}
				
				if ($key == "toDate" && $value != null) {
					$select->where ( 'product_creation_time <= ?', $value );
				}
				
				if ($key == "status" && ($value == "0" || $value == "1")) {
					$select->where ( 'product_status = ?', $value );
				}
				
				//SALE
				if ($key == 'saleoff') {
					$select->where ( 'product_saleoff_status = 1' );
				}
				
				if ($key == 'saleoff_continue' && $value = 'yes') {
					$select->where ( 'product_saleoff_end  > ' . time () );
				}
				
				if ($key == 'hot') {
					$select->where ( 'product_hot = 1' );
				}
				if ($key == "manufactureStatus" && ($value == "0" || $value == "1")) {
					$select->where ( 'manufacture_status = ?', $value );
				}
			} // end foreach
		} // end if
		
		if ($sortBy == null) {
			$sortBy = 'product_creation_time';
			$sortType = 'Desc';
		}
		$select->order ( $sortBy . ' ' . $sortType );
		
		return $this->fetchAll ( $select );
	}
}